<?php

namespace app\api\controller;

use app\admin\model\Words;
use app\admin\model\WordsDetails;
use app\api\model\BrushWords;
use app\api\model\PkLog;
use app\api\model\RecitingStudy;
use app\api\model\RecitingWordsLog;
use app\api\model\TextBooks;
use app\api\model\UserRecitingPlan;
use app\common\controller\Api;
use think\Db;
use think\Log;
use think\Request;

class Reciting extends Api
{
    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['delWords'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    private $wordsDetails;

    private $recitingWordsLog;

    private $words;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);

        $this->words = new Words();
        $this->recitingWordsLog = new RecitingWordsLog();
        $this->wordsDetails = new WordsDetails();
    }

    /**
     * 设置、修改计划
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getSetting()
    {
        $books = TextBooks::where([
            'versionId' => request()->get('version_id'),
        ])->find();
        $userRecitingPlan = new UserRecitingPlan();

        $planInfo = $userRecitingPlan->where([
            'user_id' => $this->auth->id,
        ])->find();
        $increments = [5, 10, 25, 50];
        $incrementIndex = 0;
        $current = 0; // 当前值
        $day = 0; // 当前天数
        $increment = 0; // 当前增量
        $count = [];
        $days = [];
        while ($current < $books->wordsCount) {
            if ($day >= 10 && $day < 20) {
                $increment = $increments[1];
            } elseif ($day >= 20 && $day < 30) {
                $increment = $increments[2];
            } elseif ($day >= 30) {
                $increment = $increments[3];
            } else {
                $increment = $increments[0];
            }
            $current += $increment;
            $count[] = $current;
            $days[] = ceil($books->wordsCount / $current);

            if ($current >= $books->wordsCount)
                break;
            $day++;
        }
        $count[count($count)-1] = $books->wordsCount;
        $newday = [];
        foreach ($days as $key=>$value){
            if (isset($newday[$value])){
                unset($days[$key]);
                unset($count[$key]);
                continue;
            }
            if($value * $count[$key] > $books->wordsCount){
                $newday[$value] = $key;
            }

        }

        shuffle($days);
rsort($days);
        shuffle($count);
        sort($count);
        $index = 0;
        if(!empty($planInfo)){
            foreach ($days as $k =>$val){
                if($val==$planInfo->end_day){
                    $index = $k;
                }
            }
        }

        $this->success(null, [
            'days' => $days,
            'count' => $count,
            'index' =>$index
        ]);
    }

    /**
     * 背单词首页
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $userRecitingPlan = new UserRecitingPlan();

        $planInfo = $userRecitingPlan->where([
            'user_id' => $this->auth->id,
        ])->find();
        if (!$planInfo)
            $this->error('暂无课程选择',['isset'=>false]);

        $endTime = $planInfo->createtime + (intval($planInfo->end_day) * 86400);

        // 单词总数
        $wordsCount = $this->words->where('versionId', $planInfo->version_id)->count();
        // 已学完数
        $yesCount = $this->recitingWordsLog->alias('a')
            ->where([
                'a.user_id' => $this->auth->id,
                'a.version_id' => $planInfo->version_id,
            ])
            ->count();
        // 今日学习数
        $todayCount = $this->recitingWordsLog->where([
            'user_id' => $this->auth->id,
            'version_id' => $planInfo->version_id,
        ])->where('date', '=', date('Y-m-d'))->count();
        $todayCount = $planInfo->count-$todayCount;
        // 答错数
        $todayNoCount = $this->recitingWordsLog->where([
            'user_id' => $this->auth->id,
            'status' => '0',
            'version_id' => $planInfo->version_id,
        ])->where('createtime', '>=', strtotime(date('Y-m-d')))->count();

        // 教材
        $books = TextBooks::where([
            'versionId' => $planInfo->version_id,
        ])->find();

        $result = [
            'end_day' => floor(($endTime - time()) / 86400),
            'plan_count' => $planInfo->count,
            'today_count' => $todayCount<0 ? 0 : $todayCount,
            'words_count' => $wordsCount,
            'yes_count' => $yesCount,
            'today_no_count' => $todayNoCount,
            'version_full_name' => $books->versionFullName,
            "version_full_name_id" => $books->versionId,
            'finish_day' => $planInfo->end_day,
            'date'=>$planInfo->date,
            'isset'=>true
        ];

        $this->success('成功', $result);
    }

    /**
     * 修改计划
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function updatePlan()
    {
        $data = request()->post();

        $plan = UserRecitingPlan::where([
            'user_id' => $this->auth->id,
        ])->find();

        if (!$plan) {
            $data['user_id'] = $this->auth->id;
            $data['createtime'] = time();
            UserRecitingPlan::create($data);
        } else {
            $data['createtime'] = time();
            $plan->save($data);
        }

        $this->success("操作成功");
    }

    /**
     * 获取单词列表
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getWordsList()
    {
//        $versionId = request()->get('versionId');
//        Log::info("getWordsList====$versionId===");
//        if (!$versionId)
//            $this->error('参数有误');

        $plan = UserRecitingPlan::where([
            'user_id' => $this->auth->id,
        ])->find();
        if(empty($plan)){
            $this->error('暂无课程选择');
        }
        $versionId = $plan->version_id;
        $res = [];
        $type = $this->request->param('page');
        $log = RecitingWordsLog::where(['version_id'=>$versionId])
            ->where('user_id',$this->auth->id)
            ->where('date',date('Y-m-d'))
            ->where('page',$type)
            ->find();
        if(empty($log)){
            $wordsList = $this->get($type,$versionId);
        }else{
           $wordsList = $this->get($type,$versionId,$log['did']);
        }
        Log::write($wordsList,'error');
        foreach ($wordsList as $wordsInfo) {
            $list = [];
            $words = $this->wordsDetails->where([
                'dId' => $wordsInfo->interpretationId,
                'versionId' => $versionId,
            ])->find();
            $words['status'] = RecitingWordsLog::where([
                'user_id'=>$this->auth->id,
                'version_id'=>$versionId,
                'wd_id'=> $wordsInfo->interpretationId
            ])->find() ? true : false;
            $otherList = $this->wordsDetails->where([
                'versionId' => $versionId
            ])->where('dId', '<>', $wordsInfo->interpretationId)->orderRaw('rand()')
                ->limit(3)->select();
            $list[] = $words;
            $list = array_merge($list, $otherList);
            shuffle($list);
            foreach ($list as $v) {
                if(!empty($v) && !empty($v->wordFile)){
                    $v->wordFile = $v->wordFile ? cdnurl($v->wordFile, true):'';
                    $v->wordPic =  $v->wordPic ? cdnurl($v->wordPic, true): '';
                }
            }

            $res[] = [
                'wordsInfo' => $words,
                'list' => $list,
                'count'=> $plan->count
            ];
        }

        $this->success('成功', $res);
    }

    public function get($type,$versionId,$id=''){
        if($id!=''){
            $wordsList = $this->words->alias('a')
                ->where(['a.interpretationId' => $id])
                ->field('a.interpretationId')
                ->limit(1)->select();
            return $wordsList;
        }else{
            $wordsList = $this->words->alias('a')
                ->join($this->recitingWordsLog->getTable() . " b", 'a.interpretationId = b.did', 'left')
                ->whereNull('b.id')
                ->where(['a.versionId' => $versionId])
                ->field('a.interpretationId')
                ->page($type)->limit(1)->select();
            if(empty($wordsList)){
                return $this->get($type+1,$versionId);
            }else{
                return$wordsList;
            }
        }

    }
    /**
     * 添加学习单词日志
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addStudyLog()
    {
        $wordsId = request()->post('wordsId');

        if (!isset($wordsId) || empty($wordsId))
            $this->error('参数有误');
        $userRecitingPlan = new UserRecitingPlan();
        $planInfo = $userRecitingPlan->where([
            'user_id' => $this->auth->id,
        ])->find();

        $model = new RecitingStudy();
        $data = [
            'user_id' => $this->auth->id,
            'version_id' => $planInfo->version_id,
            'words_id' => $wordsId,
        ];
        $model->save($data);

        $this->success(null, 'ok');
    }

    /**
     * 已学未学
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function studyOrNo()
    {
        $type = request()->get('type', 1);

        $userRecitingPlan = new UserRecitingPlan();
        $planInfo = $userRecitingPlan->where([
            'user_id' => $this->auth->id,
        ])->find();
        $model = new RecitingStudy();
        $words = new Words();
        if ($type == 1) {
            $limit = request()->get('limit', 5);
            $page = request()->get('page', 1);
            $result = [];
            $dateList = $model->fieldRaw("DATE_FORMAT(FROM_UNIXTIME(createtime), '%Y-%m-%d') as `date`")
                ->where('user_id', $this->auth->id)
                ->group('date')
                ->order('date', 'desc')
                ->where(['version_id'=>$planInfo->version_id])
                ->page($page,$limit)
                ->select();
            $wordList = [];
            foreach ($dateList as $v) {
                $startTime = strtotime($v->date . '00:00:00');
                $endTime = strtotime($v->date . '23:59:59');

                $list = $model->alias('a')->join($words->getTable() . ' b', 'a.words_id = b.interpretationId', 'left')
                    ->field('b.wordName, a.*')
                    ->where([
                        'a.user_id' => $this->auth->id,
                        'b.versionId' => $planInfo->version_id
                    ])->where('a.createtime', '>=', $startTime)
                    ->where('a.createtime', '<=', $endTime)
                    ->select();

                $wordList= [] ;
                foreach ($list as $vv) {
                    $wordList[] = [
                        'words_name' => $vv->wordName,
                        'words_id' => $vv->words_id,
                        'versionId'=>$vv->version_id
                    ];
                }
                $result[] = [
                    'wordsList' => $wordList,
                    'date' => $v->date,
                ];
            }

            $this->success(null, $result);
        } else {
            $limit = request()->get('limit', 10);
            $page = request()->get('page', 1);

            $study = $model->where([
                'user_id' => $this->auth->id,
            ])->field('words_id')->select();
            $wordsIds = [];
            if ($study)
                foreach ($study as $v) {
                    $wordsIds[] = $v->words_id;
                }
            $bookWordsList = $words->where([
                'versionId' => $planInfo->version_id,
            ]);
            if (count($wordsIds) > 0) {
                $bookWordsList = $bookWordsList->whereNotIn('interpretationId', $wordsIds);
            }
            $bookWordsList = $bookWordsList->limit($limit)->page($page)->select();

            $this->success(null, $bookWordsList);
        }
    }

    /**
     * 单词详情
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getWordsInfo()
    {
        $id = request()->get('words_id', null);
        $wordname = request()->get('versionId', null);
        if (!$id) $this->error('参数有误');
        $info = WordsDetails::where([
            'dId' => $id,
        ])->where(['versionId'=>$wordname])->find();
        if (empty($info)){
            $this->error('无单词详情');
        }
        $info->wordFile = !empty($info->wordFile) ? cdnurl($info->wordFile, true):'';
        $info->wordPic = !empty($info->wordPic) ? cdnurl($info->wordPic, true) : '';

        $this->success(null, $info);
    }

    /**
     * 答题
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function selectData()
    {
        // 当前单词id
        $dIds = request()->post('did');
        $dIds = explode(",", $dIds);

        // 答题id
        $ids = request()->post('id');
        $ids = explode(",", $ids);

        if (!$ids || !$dIds)
            $this->error('参数有误');

        if (count($ids) != count($dIds))
            $this->error("参数有误");
        $userRecitingPlan = new UserRecitingPlan();
        $planInfo = $userRecitingPlan->where([
            'user_id' => $this->auth->id,
        ])->find();
        foreach ($dIds as $k => $dId) {
            $id = $ids[$k];
            $detailInfo = $this->wordsDetails->where([
                'dId' => $dId,
                'versionId' => $planInfo->version_id,
            ])->find();

            $status = "1";
            if ($detailInfo->id != $id)
                $status = "0";

            // 判断该单词是否已经答过
            $has = $this->recitingWordsLog->where([
                'user_id' => $this->auth->id,
                'did' => $dId,
            ])->find();
            $count = $this->recitingWordsLog->where([
                'user_id' => $this->auth->id,
                'version_id' => $planInfo->version_id,
                'date' => date('Y-m-d'),
            ])->count();
            if ($has) {
                $has->wd_id = $id;
                $has->status = $status;
                $has->save();
            } else {
                $data = [
                    'user_id' => $this->auth->id,
                    'did' => $dId,
                    'wd_id' => $id,
                    'version_id' => $detailInfo->versionId,
                    'status' => $status,
                    'date'=>date('Y-m-d'),
                    'page'=>$count+1
                ];

                $this->recitingWordsLog->insert($data);
            }
            $model = new RecitingStudy();
            $res = $model->where(['words_id'=>$dId,'user_id'=>$this->auth->id,'version_id'=>$detailInfo->versionId])->find();
            if(empty($res)){
                $model->insert([
                    'user_id'=>$this->auth->id,
                    'words_id'=>$dId,
                    'version_id'=>$detailInfo->versionId,
                    'createtime'=>time()
                ]);
            }
        }

        $this->success('成功');
    }

    /**
     * 获取教材分类
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getBookCategory()
    {
        $book = new TextBooks();

        $res[] = [
            'periodName' => '全部',
            'child' => [],
        ];

        $periodList = $book->group('periodName')->field(['periodName'])->select();

        foreach ($periodList as $period) {
            $bookList = $book->where([
                'periodName' => $period->periodName,
            ])->field('versionName')->group('versionName')->select();

            $period->child = $bookList;
        }

        $res = array_merge($res, $periodList);

        $this->success(null, [
            'periodList' => $res,
        ]);
    }

    /**
     * 教材列表
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function bookList()
    {
        $book = new TextBooks();
        $result = [];

        $periodName = request()->get('periodName', null);
        $versionName = request()->get('versionName', null);

        if ((!isset($periodName) && empty($periodName)) || $periodName == "全部") {
            $periodName = $book->group('periodName')->select();

            foreach ($periodName as $name) {
                $list = $book->where([
                    'periodName' => $name->periodName,
                ])->order('orderNum', 'asc');

                if ($versionName != null) {
                    $list = $list->where([
                        'versionName' => $versionName,
                    ]);
                }

                $list = $list->select();

                $result[] = [
                    'bookName' => $name->periodName,
                    'list' => $list,
                ];
            }
        } else {
            $list = $book->where([
                'periodName' => $periodName,
            ])->order('orderNum', 'asc');

            if ($versionName != null) {
                $list = $list->where([
                    'versionName' => $versionName,
                ]);
            }

            $list = $list->select();

            $result[] = [
                'bookName' => $periodName,
                'list' => $list,
            ];
        }

        $this->success(null, $result);
    }

    /**
     * 单词pk首页
     * @return void
     * @throws \think\Exception
     */
    public function pkIndex()
    {
        $model = new PkLog();
        $count = $model->where([
            'user_id' => $this->auth->id,
        ])->count();

        $yesCount = $model->where([
            'user_id' => $this->auth->id,
            'type' => 1,
        ])->count();

        $this->success(null, [
            'count' => $count,
            'rate' => ($yesCount == 0 || $count == 0) ? 0 : ceil($yesCount / $count) * 100,
            'yesCount' => $yesCount,
        ]);
    }

    /**
     * 单词pk
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function pk()
    {
        $res = [];
        $list = $this->wordsDetails->group('words')->orderRaw("rand()")->limit(5)->select();
        foreach ($list as &$info) {
            $otherWordsList = [];
            $info->wordFile = cdnurl($info->wordFile, true);
            $info->wordPic = cdnurl($info->wordPic, true);
            $otherWordsList2 = $this->wordsDetails->group('words')
                ->where('words', $info->words)
                ->select();
            $otherWordsList = $this->wordsDetails->group('words')
                ->whereOr('id', '<>', $info->id)
                ->orderRaw("rand()")->limit(3)
                ->select();
//            $otherWordsList = array_merge($otherWordsList1, $otherWordsList2);
//            shuffle($otherWordsList);
            foreach ($otherWordsList as $value) {
                $value->wordFile = cdnurl($value->wordFile, true);
                $value->wordPic = cdnurl($value->wordPic, true);
            }
            $info['falseList'] = $otherWordsList;
        }
        $otherUser = \app\common\model\User::where('id', '<>', $this->auth->id)->where('type',3)->orderRaw('rand()')->limit(1)->find();
        $res['otherUser'] = $otherUser;
        $res['wordsList'] = $list;
        $this->success(null, $res);
    }

    /**
     * 保存pk结果
     * @return void
     */
    public function savePk()
    {
        $prams = request()->post();
        $data = [
            'user_id' => $this->auth->id,
            'type' => $prams['type'],
        ];

        $model = new PkLog();
        $model->save($data);

        $this->success();
    }

    public function getPkLog(){
        $prams = request()->post();
        $model = new PkLog();
        $list = $model->where([
            'user_id' => $this->auth->id,
            'target_user_id' => $prams['target_user_id'],
        ])->find();
        $this->success(null, $list);
    }
    /**
     * 添加刷单词记录
     * @return void
     */
    public function addWords()
    {
        $param = request()->post();
        $data = BrushWords::where(['user_id'=>$this->auth->id,
            'words_id' => $param['words_id'],
            'words' => $param['words'],
        ])->find();
        if($data){
            if($data['score'] < $param['score']){  //新评分大于原来评分更新
                BrushWords::where(['id'=>$data['id']])->update([
                    'score' =>$param['score'],
                    'myvideosource' =>$param['myvideosource'],
                    'updatetime'=>time()
                ]);
            }else{
                BrushWords::where(['id'=>$data['id']])->update([
                    'updatetime'=>time()
                ]);
            }
        }else{
            $insert = [
                'user_id' => $this->auth->id,
                'words_id' => $param['words_id'],
                'score' => $param['score'],
                'words' => $param['words'],
                'wordsjson' =>htmlspecialchars_decode(input('wordsjson')),
                'myvideosource' => $param['myvideosource'],
            ];
            $model = new BrushWords($insert);
            $model->allowField(false)->save();
        }
        $this->success(null, "成功");
    }

    /**
     * 刷单词列表
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function brushWordsList() {
        //$this->auth->id = 1;
        $limit = request()->get('limit', 10);
        $page = request()->get('page', 1);
        //echo $this->auth->id;
        $model = new BrushWords();
        $list = $model
            //->with('wordsDetail')
            ->where([
            'user_id' => $this->auth->id,
            //'user_id' => 9,
        ])->order('updatetime asc')->limit($limit)->page($page)->select();
        foreach ($list as &$v){
            $json = json_decode($v['wordsjson'],true);
            $json['wordFile'] = \request()->domain().'/file/repeat/res/'.$json['wordFile'];
            $json['wordPic'] = \request()->domain().'/file/repeat/res/'.$json['wordPic'];
            $v['wordsjson'] = $json;
            $v->myvideosource_domain = NULL;
            if($v->myvideosource){
                $v->myvideosource_domain = \request()->domain().$v->myvideosource;
            }
            /*if(empty($v->words_detail)){

            }else{
                $v->words_detail->wordFile = \request()->domain().$v->words_detail->wordFile;
                $v->words_detail->wordPic = \request()->domain().$v->words_detail->wordPic;
            }*/

            //var_dump($v);die();
            //$v['myvideosource_domain'] = cdnurl($v['myvideosource_domain'], true);
        }

        $this->success(null, $list);
    }

    /**
     * 单词详情
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function wordsInfo()
    {
        $id = request()->get('id', null);

        $model = new BrushWords();
        $info = $model
            //->with('wordsDetail')
            ->findOrFail($id);

        $json = json_decode($info['wordsjson'],true);
        $json['wordFile'] = \request()->domain().'/file/repeat/res/'.$json['wordFile'];
        $json['wordPic'] = \request()->domain().'/file/repeat/res/'.$json['wordPic'];
        $info['wordsjson'] = $json;
/*
        if(strpos($info->words_detail->wordFile,'/file/words') === false){
            $info->words_detail->wordFile =  \request()->domain().'/file/phonetic_symbol/res/'.$info->words_detail->wordFile;
            $info->words_detail->wordPic =  \request()->domain().'/file/phonetic_symbol/res/'.$info->words_detail->wordPic;
        }else{
            $info->words_detail->wordFile =  \request()->domain().'/'.$info->words_detail->wordFile;
            $info->words_detail->wordPic =  \request()->domain().'/'.$info->words_detail->wordPic;
        }*/


        $info->myvideosource_domain = NULL;
        if($info->myvideosource){
            $info->myvideosource_domain =  \request()->domain().$info->myvideosource;
        }
        //$info->myvideosource = cdnurl($info->myvideosource, true);

        $this->success(null, $info);
    }

    //更新单词
    public function saveWords()
    {
        $param = request()->post();
        $data['user_id'] = $this->auth->id;
        $model = new BrushWords();
        $data = $model->where(['id'=>$param['id']])->find();
        if($data['score'] < $param['score']){
            $model->where(['id'=>$param['id']])->update([
                'score' =>$param['score'],
                'myvideosource' =>$param['myvideosource'],
                'updatetime'=>time()
            ]);
        }
        $this->success(null, "成功");
    }

    public function delWords(){
        $model = new Words();
        $page = Db::name('page')->count();
        $words = $model->page($page+1)->limit(300)->select();
        $wordsDetail = new WordsDetails();
        foreach ($words as $word){
            $info = $wordsDetail->where('dId',$word['interpretationId'])
                ->where(['versionId'=>$word['versionId']])->find();
            if(empty($info)){
                $word->delete();
            }

        }
        Db::name('page')->insert(['page'=>$page+1]);
    }
}